﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

namespace WsHelp.UI
{
    /// <summary>
    /// 获取显示屏的分辨率、缩放比例、光标位置、某个点的像素
    /// </summary>
    public class PrimaryScreen
    {
        #region Win32 API
        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr ptr);

        /// <summary>
        /// 获取设备某个性能值
        /// </summary>
        /// <param name="ptr">设备指针</param>
        /// <param name="nIndex">某个性能的索引</param>
        /// <returns></returns>
        [DllImport("gdi32.dll")]
        static extern int GetDeviceCaps(IntPtr ptr, int nIndex);

        /// <summary>
        /// 获取光标实际位置（未缩放的位置）
        /// </summary>
        [DllImport("user32.dll")]
        static extern bool GetCursorPos(out System.Drawing.Point point);

        /// <summary>
        /// 获取某个坐标的像素值：参数x,y坐标为缩放后的值，才能准确定位到屏幕某个点的像素
        /// </summary>
        [DllImport("gdi32.dll")]
        static extern uint GetPixel(IntPtr hDc, int nXpos, int nYpos);

        [DllImport("user32.dll", EntryPoint = "ReleaseDC")]
        static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc);
        #endregion

        #region DeviceCaps常量
        const int HORZRES = 8;
        const int VERTRES = 10;
        const int LOGPIXELSX = 88;
        const int LOGPIXELSY = 90;
        const int DESKTOPVERTRES = 117;
        const int DESKTOPHORZRES = 118;
        #endregion

        #region 属性
        /// <summary>
        /// 获取屏幕分辨率物理大小（缩放前的大小）
        /// </summary>
        public static Size WorkingArea
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                Size size = new Size();
                size.Width = GetDeviceCaps(hdc, HORZRES);
                size.Height = GetDeviceCaps(hdc, VERTRES);
                ReleaseDC(IntPtr.Zero, hdc);
                return size;
            }
        }
        /// <summary>
        /// 获取屏幕分辨率实际大小（缩放后的大小）
        /// </summary>
        public static Size DesktopSize
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                Size size = new Size();
                size.Width = GetDeviceCaps(hdc, DESKTOPHORZRES);
                size.Height = GetDeviceCaps(hdc, DESKTOPVERTRES);
                ReleaseDC(IntPtr.Zero, hdc);
                return size;
            }
        }
        /// 
        /// 当前系统DPI_X 大小 一般为96
        /// 
        public static int DpiX
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                int DpiX = GetDeviceCaps(hdc, LOGPIXELSX);
                ReleaseDC(IntPtr.Zero, hdc);
                return DpiX;
            }
        }
        /// 
        /// 当前系统DPI_Y 大小 一般为96
        /// 
        public static int DpiY
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                int DpiX = GetDeviceCaps(hdc, LOGPIXELSY);
                ReleaseDC(IntPtr.Zero, hdc);
                return DpiX;
            }
        }
        /// 
        /// 获取宽度缩放百分比
        /// 
        public static float ScaleX
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                float ScaleX = (float)GetDeviceCaps(hdc, DESKTOPHORZRES) / (float)GetDeviceCaps(hdc, HORZRES);
                ReleaseDC(IntPtr.Zero, hdc);
                return ScaleX;
            }
        }
        /// 
        /// 获取高度缩放百分比
        /// 
        public static float ScaleY
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                float ScaleY = (float)(float)GetDeviceCaps(hdc, DESKTOPVERTRES) / (float)GetDeviceCaps(hdc, VERTRES);
                ReleaseDC(IntPtr.Zero, hdc);
                return ScaleY;
            }
        }
        /// <summary>
        /// 光标位置的像素颜色
        /// </summary>
        public static Color CursorPixelColor
        {
            get
            {
                GetCursorPos(out Point pt);
                return PixelColor(pt);
            }
        }
        #endregion


        /// <summary>
        /// 获取某个位置的像素颜色（物理位置）
        /// </summary>
        public static Color PixelColor(Point pos)
        {
            IntPtr hdc = GetDC(IntPtr.Zero);
            float ScaleX = (float)GetDeviceCaps(hdc, DESKTOPHORZRES) / (float)GetDeviceCaps(hdc, HORZRES);
            float ScaleY = (float)(float)GetDeviceCaps(hdc, DESKTOPVERTRES) / (float)GetDeviceCaps(hdc, VERTRES);
            uint pixel = GetPixel(hdc, (int)(pos.X * ScaleX), (int)(pos.Y * ScaleY));
            ReleaseDC(IntPtr.Zero, hdc);

            Color color = Color.FromArgb(
                (int)(pixel & 0x000000FF),
                (int)(pixel & 0x0000FF00) >> 8,
                (int)(pixel & 0x00FF0000) >> 16
                );

            return color;
        }
    }

    /// <summary>
    /// 自适应屏幕缩放比例截图
    /// </summary>
    public class ScreenShot
    {
        Point _startPoint, _endPoint;
        Point _startPointTmp, _endPointTmp;
        Size _captrueSize = new Size(0, 0);
        bool _saveFile = true;
        bool _startCaptrue = false;
        bool _mouseDown = false;
        bool _havePainted = false;
        Form _form;
        float _scale;

        private static readonly ScreenShot _instance = new ScreenShot();
        private ScreenShot() { }
        public static ScreenShot Instance => _instance;

        /// <summary>
        /// 自动从屏幕截图：指定起始坐标、大小、是否保存文件
        /// </summary>
        /// <param name="startPoint">屏幕起始坐标</param>
        /// <param name="captrueSize">截取大小</param>
        /// <param name="isSaveFile">是否保存文件</param>
        public static void CaptrueScreen(Point startPoint, Size captrueSize, bool isSaveFile)
        {
            float scale = PrimaryScreen.ScaleX;

            if (startPoint.X < 0) startPoint.X = 0;
            if (startPoint.Y < 0) startPoint.Y = 0;

            startPoint.X = (int)(startPoint.X * scale);
            startPoint.Y = (int)(startPoint.Y * scale);
            captrueSize.Width = (int)(captrueSize.Width * scale);
            captrueSize.Height = (int)(captrueSize.Height * scale);

            CaptrueScaledScreen(startPoint, captrueSize, isSaveFile);
        }

        /// <summary>
        /// 手动拖动鼠标截图
        /// </summary>
        /// <param name="isSaveFile">是否保存文件</param>
        public void StartCaptrue(bool isSaveFile)
        {
            _scale = PrimaryScreen.ScaleX;

            _form = new Form();
            _form.MouseDown += Form1_MouseDown;
            _form.MouseMove += Form1_MouseMove;
            _form.MouseUp += Form1_MouseUp;

            _form.Opacity = 0.01;
            _form.FormBorderStyle = FormBorderStyle.None;
            _form.WindowState = FormWindowState.Maximized;

            _startCaptrue = true;
            _saveFile = isSaveFile;

            _form.Show();
        }

        private Point LocationScale(Point p)
        {
            return new Point((int)(p.X * _scale), (int)(p.Y * _scale));
        }

        private static void CaptrueScaledScreen(Point startPoint, Size captrueSize, bool isSaveFile)
        {
            try
            {
                Bitmap bit = new Bitmap(captrueSize.Width, captrueSize.Height);
                Graphics g = Graphics.FromImage(bit);
                g.CopyFromScreen(startPoint, new Point(0, 0), bit.Size);
                if (isSaveFile)
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.FileName = "ScreenShot_" + DateTime.Now.ToString("yyyy-MM-dd_HHmmss");
                    saveFileDialog.Filter = "png|*.png|bmp|*.bmp|jpg|*.jpg|gif|*.gif";
                    if (saveFileDialog.ShowDialog() != DialogResult.Cancel)
                    {
                        bit.Save(saveFileDialog.FileName);
                    }
                }
                else
                {
                    Clipboard.SetImage(bit);
                }
                g.Dispose();
            }
            catch (Exception e)
            {
                MessageBox.Show("CaptrueScreen Error: " + e.Message);
            }
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            if (!_startCaptrue) return;

            _startPoint = LocationScale(e.Location);
            _mouseDown = true;
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            if (!_startCaptrue) return;

            _startCaptrue = false;
            _mouseDown = false;

            if (_captrueSize.Width != 0 && _captrueSize.Height != 0)
            {
                // 将上次绘制的方框清除
                ControlPaint.DrawReversibleFrame(new Rectangle(_startPointTmp, _captrueSize), Color.Transparent, FrameStyle.Dashed);
                _havePainted = false;
            }

            _endPoint = LocationScale(e.Location);

            if (_startPoint.X > _endPoint.X)
            {
                int temp = _endPoint.X;
                _endPoint.X = _startPoint.X;
                _startPoint.X = temp;
            }

            if (_startPoint.Y > _endPoint.Y)
            {
                int temp = _endPoint.Y;
                _endPoint.Y = _startPoint.Y;
                _startPoint.Y = temp;
            }
            _form.Opacity = 0.0;

            _captrueSize.Width = _endPoint.X - _startPoint.X;
            _captrueSize.Height = _endPoint.Y - _startPoint.Y;

            Thread.Sleep(200);

            if (_captrueSize.Width > 0 && _captrueSize.Height > 0)
            {
                CaptrueScaledScreen(_startPoint, _captrueSize, _saveFile);
            }

            _form.WindowState = FormWindowState.Normal;
            _form.FormBorderStyle = FormBorderStyle.FixedSingle;
            _form.Opacity = 1;

            _form.Close();
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!_startCaptrue) return;

            if (_mouseDown)
            {
                if (_captrueSize.Width != 0 && _captrueSize.Height != 0 && _havePainted)
                {
                    // 将上次绘制的方框清除
                    ControlPaint.DrawReversibleFrame(new Rectangle(_startPointTmp, _captrueSize), Color.Transparent, FrameStyle.Dashed);
                }

                _endPointTmp = LocationScale(e.Location);
                _captrueSize.Width = Math.Abs(_endPointTmp.X - _startPoint.X);
                _captrueSize.Height = Math.Abs(_endPointTmp.Y - _startPoint.Y);
                _startPointTmp.X = (_startPoint.X > _endPointTmp.X) ? _endPointTmp.X : _startPoint.X;
                _startPointTmp.Y = (_startPoint.Y > _endPointTmp.Y) ? _endPointTmp.Y : _startPoint.Y;

                if (_captrueSize.Width != 0 && _captrueSize.Height != 0)
                {
                    // 绘制方框
                    ControlPaint.DrawReversibleFrame(new Rectangle(_startPointTmp, _captrueSize), Color.Transparent, FrameStyle.Dashed);
                    _havePainted = true;
                }
            }
        }
    }
}
